package com.android.locationapi.maps;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.Toast;


import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;


public class ShowMap extends MapActivity {
	
	private MyLocationOverlay locationOverlay;
	 
	 private LocationManager lm;
	 GeoPoint gp;

	private MapController mapController;
	private MapView mapView;
	private LocationManager locationManager;
	Location location ;

	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.map); // bind the layout to the activity

		Log.v("SHOW MAP", "In show map");
		// create a map view
		RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.maplayout);
		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mapView.setStreetView(true);
		mapController = mapView.getController();
		mapController.setZoom(14); // Zoom 1 is world view
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, new GeoUpdateHandler());
		
		
		//List<Overlay> mapOverlays = mapView.getOverlays();
		
		 List<Overlay> mapOverlays = mapView.getOverlays();
		    Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
		    HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
		    
		   // locationOverlay.enableMyLocation();

		  lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		  lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0 * 1000, 0, new GeoUpdateHandler() );
		   Location lastKnownLoc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		  
		   Location lastLocation = lm.getLastKnownLocation( LocationManager.NETWORK_PROVIDER );
		    if ( lastLocation != null )
		    {
		   
try{
		   
		     int longTemp = (int)(lastKnownLoc.getLongitude()* 1000000);
		     int latTemp = (int)(lastKnownLoc.getLatitude() * 1000000);
		     gp =  new GeoPoint(latTemp, longTemp);
		     Log.v("SHOW MAP", "Sent " + longTemp);
       	  Log.v("SHOW MAP", "Sent " + latTemp);
       
}
catch (NullPointerException e)
{
	
}
		    }
		   //GeoPoint point = locationOverlay.getMyLocation();
		   GeoPoint point2 = new GeoPoint(44410000, -788960000);
		    OverlayItem overlayitem2 = new OverlayItem(gp, "That's me", serv.sessionusername);
		
		    
			itemizedoverlay.addOverlay(overlayitem2);
		    mapOverlays.add(itemizedoverlay);
		    

		    
		    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
 	        nameValuePairs.add(new BasicNameValuePair("username",creden.usernme));
   	        nameValuePairs.add(new BasicNameValuePair("threshold",settings._threshold));
   	       
	            InputStream is = null;
  	        String result = "";

 	          try{
 	        	  
	                  HttpClient httpclient = new DefaultHttpClient();
	                  HttpPost httppost = new HttpPost(serveripaddress.servipaddr+"threshold.php");
	                  httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	                  Log.v("Ramya", "AddFriends I am done 1!!!");
	                  HttpResponse response = httpclient.execute(httppost);
	                  Log.v("Ramya", "AddFriends I am done 2!!!");
	                  HttpEntity entity = response.getEntity();
	                  Log.v("Ramya", "AddFriends here now");
	                  is = entity.getContent();
	                  Log.v("Ramya: Returned from the server 0 : ", is.toString());

	          }
 	          catch(Exception e)
 	          {
	                  Log.v("log_tag", "Error in http connection "+e.toString());
	          }
	          //convert response to string
	          try{
	                  BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	                  StringBuilder sb = new StringBuilder();
	                  String line = null;
	                  while ((line = reader.readLine()) != null) {
	                          sb.append(line);
	                  }
	                  is.close();
	           
	                  result=sb.toString();
	               Log.v("Ramya 1: Returned from the server : ", result);
	               String[] res_array = result.split(",",-1);
	                  //if ( result.equals(""))
	               int j;
	               int q;
	            for(int i=0; i<res_array.length; i++) {
	            Log.v("Ramya 2: Returned from the server : ", res_array[i]);
	            j=i%5;
	            q=i/5;
	            if(j==4) {
	            if (Integer.parseInt(res_array[q*5+j])==1) {
	            	Toast.makeText(this.getApplicationContext()," " + res_array[q*5+j-3] + " is within range", 9000).show();
	            	int latitude= (int)(Double.parseDouble(res_array[q*5+j-2])*1000000);
	            	int longitude= (int)(Double.parseDouble(res_array[q*5+j-1])*1000000);
	     		   GeoPoint point3 = new GeoPoint(latitude, longitude);
	   		    OverlayItem overlayitem3 = new OverlayItem(point3, "In Range",res_array[q*5+j-3]);
	   		
	   		    
	   			itemizedoverlay.addOverlay(overlayitem3);
	   		    mapOverlays.add(itemizedoverlay);
	            }	
	            else
	            {
	            	Toast.makeText(this.getApplicationContext()," " + res_array[q*5+j-3] + " is outside range", 9000).show();
	            }
	            }
	            }
	          }

	          catch(Exception e){
	                  Log.v("log_tag", "Error converting result "+e.toString());
	          }
		   
		    
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	Log.v("Ramya", "in here after intent");
	    switch (item.getItemId()) {
	        case R.id.addFriendsText:         	
	        	Intent myIntent = new Intent(ShowMap.this, AddFriend.class);
	        	ShowMap.this.startActivity(myIntent);
                break;
                
	        case R.id.settingsText:     
	        	Intent myIntent5 = new Intent(ShowMap.this, settings.class);
	        	ShowMap.this.startActivity(myIntent5);
                break;

	        case R.id.viewFriendsText:     
	        	Log.v("Ramya", "in here after intent");
	        	Intent myIntent1 = new Intent(ShowMap.this, displayfriends.class);
	        	ShowMap.this.startActivity(myIntent1);
	        	break;

	        case R.id.deleteFriendsText:     
	        	Log.v("Ramya", "in here after intent");
	        	Intent myIntent2 = new Intent(ShowMap.this, deleteFriend.class);
	        	ShowMap.this.startActivity(myIntent2);
	        	break;

	    }
	    return true;
	}
	public class GeoUpdateHandler implements LocationListener {
		
		@Override
		public void onLocationChanged(Location location) {
			int lat = (int) (location.getLatitude() * 1E6);
			int lng = (int) (location.getLongitude() * 1E6);
			GeoPoint point = new GeoPoint(lat, lng);
			mapController.animateTo(point); 
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onProviderEnabled(String provider) {
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
		

	}
}